package cn.harry.modular.portrait.service.impl;

import cn.harry.component.security.utils.SecurityUtils;
import cn.harry.modular.portrait.domain.UserSegments;
import cn.harry.modular.portrait.mapper.UserSegmentsMapper;
import cn.harry.modular.portrait.service.UserSegmentsRelationService;
import cn.harry.modular.portrait.service.UserSegmentsService;
import cn.harry.modular.portrait.service.UserService;
import cn.harry.modular.portrait.vo.PortraitUserVO;
import cn.harry.modular.portrait.vo.UserSegmentsCondition;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户分群服务实现类
 *
 * @author harry
 * @公众号 Harry技术
 */
@Service
@RequiredArgsConstructor
public class UserSegmentsServiceImpl extends ServiceImpl<UserSegmentsMapper, UserSegments> implements UserSegmentsService {

    private final UserService userService;
    private final UserSegmentsRelationService userSegmentsRelationService;

    @Override
    public boolean saveUserSegments(UserSegmentsCondition condition) {
        UserSegments userSegments = new UserSegments();
        userSegments.setSegmentSn(String.valueOf(IdWorker.getId()));
        userSegments.setSegmentName(condition.getSegmentName());
        userSegments.setPushStatus(condition.getPushStatus());
        userSegments.setCreator(SecurityUtils.getSysUser().getUsername());
        userSegments.setSelectConditions(condition.getSelectConditions());

        List<Long> userIds = userService.listUserIdsByCondition(condition);
        userSegments.setMemberCount(userIds.size());
        boolean save = this.save(userSegments);
        if (save) {
            userSegmentsRelationService.saveUserSegmentsRelation(userIds, userSegments.getId());
            return true;
        }
        return false;
    }

    @Override
    public Integer countUserSegments(UserSegmentsCondition condition) {
        List<Long> userIds = userService.listUserIdsByCondition(condition);
        return userIds.size();
    }

    @Override
    public List<PortraitUserVO> export(UserSegments entity) {

        List<PortraitUserVO> list = this.baseMapper.listPortraitUserVOBySegmentId(entity.getId());
        if (!list.isEmpty()) {
            return list;
        }
        return List.of();
    }
}
